package net.borderwars.util;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * User: hubbard
 * Date: May 6, 2006
 * Time: 10:36:57 AM
 */
public class StartupWrapper {
    public static void main (String[] args) throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        try {
            File f = new File (".");
            File names[] = f.listFiles (new FilenameFilter() {
                public boolean accept (File dir, String name) {
                    return (name.toLowerCase ().endsWith (".jar"));

                }
            });
            URL jarurls[] = new URL[names.length];
            int idx = 0;
            for (File jarFile : names) {
                URI i = jarFile.toURI ();
                jarurls[idx++] = i.toURL ();
                System.out.println (" " + jarFile.toURL ());
            }
            System.out.println ("Loaded " + idx + " jars");
            URLClassLoader cl = new URLClassLoader (jarurls, Thread.currentThread ().getContextClassLoader ());
            Thread.currentThread ().setContextClassLoader (cl);

            String[] passedArgs = new String[args.length - 1];
            System.arraycopy (args, 1, passedArgs, 0, passedArgs.length);

            final Class c = cl.loadClass (args[0]);

            final Class argTypes[] = new Class[1];
            argTypes[0] = passedArgs.getClass ();

            final Object argsss[] = new Object[1];
            argsss[0] = passedArgs;

            Thread t = new Thread (new Runnable() {
                public void run () {
                    try {

                        Method m = c.getMethod ("main", argTypes);
                        m.invoke (null, argsss);
                    }
                    catch (Throwable e) {
                        e.printStackTrace ();
                        System.exit (1);
                    }
                }
            });
            t.start ();

        }
        catch (Throwable e) {
            e.printStackTrace ();
            System.exit (1);
        }
    }
}
